package com.mcy.springbatch.job;

import com.mcy.springbatch.job.BaseJobConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 异常重启Demo,springbatch执行多个step时，某一step遇到异常退出任务，重启后会继续执行剩余未执行成功的step
 * @author : Create By mcy
 * @date : 2019/8/25 17:24:15
 */
@Slf4j
@Configuration
public class MErrorJobConfig extends BaseJobConfig {

    @Bean
    public Job errorJob() {
        return jobBuilderFactory.get("errorJob")
                .incrementer(new RunIdIncrementer())
                .start(errorJobStep1())
                .next(errorJobStep2())
                .build();
    }

    @Bean
    public Step errorJobStep1() {
        return stepBuilderFactory.get("errorJobStep1")
                .tasklet(errorJobStepTasklet())
                .build();
    }

    @Bean
    public Step errorJobStep2() {
        return stepBuilderFactory.get("errorJobStep2")
                .tasklet(errorJobStepTasklet())
                .build();
    }

    @Bean
    public Tasklet errorJobStepTasklet(){
        return (stepContribution, chunkContext) -> {
            ExecutionContext executionContext = chunkContext.getStepContext().getStepExecution().getExecutionContext();
            if(executionContext.containsKey("info")){
                log.info("执行成功");
                return RepeatStatus.FINISHED;
            }else {
                log.info("执行失败");
                chunkContext.getStepContext().getStepExecution().getExecutionContext().put("info","mcyData");
                throw new RuntimeException("执行失败");
            }
        };
    }

}
